package onlinebanking.server.objects;

import onlinebanking.constants.MSG;
import onlinebanking.network.Message;
import onlinebanking.sql.SQLConnection;
import onlinebanking.sql.SQLTable;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Announcement extends QueryObject{
	
	public static final char PERSONAL_ANNOUNCEMENT = 'S';
	public static final char GENERAL_ANNOUNCEMENT = 'G';
	public static final char POSTED = 'P';
	public static final char REMOVED = 'R';
	
	public static boolean postPersonalAnnouncement(int recepient, int sender, String announcement){
		String sqlstatement = "INSERT INTO personalannouncements(recepient,sender,announcement,announcementstatusid) " +
				"VALUES(?,?,?,?);";
		
		SQLTable sqltable = new SQLTable(SQLConnection.getInstance().getConnection());
		sqltable.setSQLStatement(sqlstatement);
		sqltable.setIntParam(1, recepient);
		sqltable.setIntParam(2, sender);
		sqltable.setStringParam(3, announcement);
		sqltable.setCharParam(4, Announcement.POSTED);
		
		int insertedPK = sqltable.executeUpdate();
		
		return (insertedPK != -1);
	}
	
	public static Message getGeneralAnnouncements(){
		Message announcements = new Message();
		announcements.setMsgType(MSG.ANNOUNCEMENTS);
		
		String sqlstatement = "SELECT announcement FROM generalannouncements " +
				"WHERE announcementstatusid = 'P';";
		
		SQLTable sqltable = new SQLTable(SQLConnection.getInstance().getConnection());
		sqltable.setSQLStatement(sqlstatement);
		
		ResultSet rs = sqltable.executeSQL();
		
		try {
			if(rs.first()){
				int i = 0;
				do{
					announcements.addAttribute("#"+i, rs.getString(1));				
					i++;
				}while(rs.next());
				announcements.addAttribute("count", i);
			}
		} catch (SQLException e) {
		}
		return announcements;
	}
	
	public static Message getPersonalAnnouncements(int personalaccountid){
		Message announcements = new Message();
		announcements.setMsgType(MSG.ANNOUNCEMENTS);
		
		String sqlstatement = "SELECT announcement FROM personalannouncements " +
				"WHERE announcementstatusid = 'P' AND recepient = ?;";
		
		SQLTable sqltable = new SQLTable(SQLConnection.getInstance().getConnection());
		sqltable.setSQLStatement(sqlstatement);
		sqltable.setIntParam(1,personalaccountid);
		
		ResultSet rs = sqltable.executeSQL();
		
		try {
			if(rs.first()){
				int i = 0;
				do{
					announcements.addAttribute("#"+i, rs.getString(1));				
					i++;
				}while(rs.next());
				announcements.addAttribute("count", i);
			}
		} catch (SQLException e) {
		}
		return announcements;
	}

}
